package com.guapi.schedule.taskCenter;

import cn.hutool.core.date.DateUtil;
import com.guapi.dao.Event;
import com.guapi.dao.Task;
import com.guapi.event.EventProducer;
import com.guapi.service.TaskService;
import com.guapi.service.UserService;
import com.guapi.util.KafkaConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

import static com.guapi.util.ConversationConstant.SYSTEM_MESSAGE;


/**
 * @author 瓜皮哦
 */
@Component
public class CommonScheduleTask implements KafkaConstant {

    @Autowired
    private TaskService taskService;

    @Autowired
    private EventProducer eventProducer;

    @Autowired
    private UserService userService;

    /**
     * 定时获取即将过期的任务列表(自定义时间)
     */
    public void findExpireTask(String expiredDay) {
        List<Task> toExpiredTasks = taskService.getToExpired(DateUtil.offsetDay(DateUtil.date(), Integer.parseInt(expiredDay)), true);
        toExpiredTasks.forEach(task -> {
            String username = userService.getUsernameById(Integer.valueOf(task.getPublisher()));
            Event event = new Event();
            event.setTopic(TOPIC_EXPIRED_TASK)
                    .setEntityType(SYSTEM_MESSAGE)
                    .setUserId(Integer.parseInt(task.getPublisher()))
                    .setData(DATA_KEY_CONTENT, String.format(EXPIRE_CONTENT,username,task.getTaskName(),task.getExpired()));
            eventProducer.sendEvent(event);
        });
    }

}
